using System.Windows;
using System.Xml;

namespace OfficeOpenXml
{
    public class DataBar : RuleVisualizer
    {        
        private XmlNode _colorNode;

        public DataBar(ConditionalFormattingRule conditionalFormatting) : base(conditionalFormatting)
        {
            _xmlNode = ConditionalFormattingRule.ConditionalFormatting.Worksheet.WorksheetXml.CreateElement("dataBar",
                                                                                                            ExcelPackage
                                                                                                                .
                                                                                                                schemaMain);
            ConditionalFormattingRule.XmlNode.AppendChild(this._xmlNode);
            Min = 0;
            Max = 0;
            ColorRGB = "FF638EC6";
        }

        public DataBar(ConditionalFormattingRule conditionalFormatting, XmlNode ruleNode) : base(conditionalFormatting, ruleNode)
        {
        }

        public string ColorRGB
        {
            get
            {                
                if (this._colorNode == null)
                {
                    this._colorNode = this.GetColorNode();
                }
                return this._colorNode.Attributes["rgb"].Value;
            }
            set
            {
                if (this._colorNode == null)
                {
                    this._colorNode = this.GetColorNode();
                }
                this._colorNode.Attributes["rgb"].Value = value;
            }
        }

        private XmlNode GetColorNode()
        {
            XmlNode node = null;            
            foreach (XmlNode childNode in this.XmlNode.ChildNodes)
            {
                if (childNode.Name == "color")
                {
                    node = childNode;
                    break;
                }
            }

            if (node == null)
            {
                XmlElement element =
                    this.ConditionalFormattingRule.ConditionalFormatting.Worksheet.WorksheetXml.CreateElement(
                        "color",
                        ExcelPackage.schemaMain);
                element.SetAttribute("rgb", "FF638EC6");
                node = element;
                XmlNode.AppendChild(node);
            }
            return node;
        }
    }
}